# -*- coding:utf-8 -*-
import web
import json
import stixconfig
from queryhandler import QueryHandler
from stixhandler import format_query_body

server_urls = (
    '/stix', 'stixindex',
    '/stix/', 'stixindex',
    '/stix/apply', 'stixapply',
    '/stix/apply/', 'stixapply'
)

webapp = web.application(server_urls, locals())


class stixindex:
    def GET(self):
        stixhelpfile = open('static/stixhelp.html', 'r', encoding='utf-8')
        return stixhelpfile.read()

    def POST(self):
        return self.GET(self)


class stixapply:
    def POST(self):
        querydata = web.data()
        if web.ctx.env.get('CONTENT_TYPE') == 'application/x-www-form-urlencoded':
            body = json.loads(querydata.get('body'))
        if web.ctx.env.get('CONTENT_TYPE') == 'application/json':
            querydata = json.loads(querydata)
            body = querydata.get('body')
        body['size'] = stixconfig.limit_count
        body['timeout'] = stixconfig.timeout

        appkey = querydata.get('appkey')
        index = querydata.get('index')
        doc_type = querydata.get('doc_type')

        # authres = json.loads(webapp.request('/appkey/verify','GET',{'appkey':appkey},stixconfig.keystone_url).data)
        authres = {}
        authres['code'] = 0
        if authres['code'] == 1:  # Illegal Appkey, ignore
            return ''
        elif authres['code'] == 2:
            return '{"code":2, "msg":"appkey过期","body":{}}'
        elif authres['code'] == 0:
            qh = QueryHandler(body=body,index=index,doc_type=doc_type)
            return qh.getresult()

    def GET(self):
        querydata = web.input()
        appkey = querydata.get('appkey')
        if querydata.get('md5'):
            # search FileScan MD5
            index = 'ttp'
            doc_type = 'DNA'
            field = 'md5'
            data = querydata.get('md5')
        else:
            index = querydata.get('index')
            doc_type = querydata.get('doc_type')
            field = querydata.get('type')
            data = querydata.get('query')

        body = format_query_body(field=field,data=data)

        # authres = json.loads(webapp.request('/appkey/verify','GET',{'appkey':appkey},stixconfig.keystone_url).data)
        authres = {}
        authres['code'] = 0
        if authres['code'] == 1:  # Illegal Appkey, ignore
            return ''
        elif authres['code'] == 2:
            return '{"code":2, "msg":"appkey过期","body":{}}'
        elif authres['code'] == 0:
            qh = QueryHandler(body=body, index=index, doc_type=doc_type)
            return qh.getresult()



def RunStixWebServer():
    try:
        webapp.run()
    except Exception, e:
        print e

if __name__ == '__main__':
    RunStixWebServer()
